<?php


namespace app\common\model;

class Collection extends Base
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'ddt_collection';
    // 主键ID
    protected $pk = 'c_id';

	public function record($user_id,$product_id,$stock_id){
	    $result = [
	        'code' => -1,
        ];
		$where = ['user_id'=>$user_id,'product_id'=>$product_id,'p_s_id'=>$stock_id];
		$info = $this
			->field($this->pk)
			->where($where)
			->find();

		if($info){
			$res = $this->where($where)->delete();
			$msg = '取消收藏成功';
		}else{
			$res = $this->save([
				'user_id'=>$user_id,
				'product_id'=>$product_id,
				'p_s_id'=>$stock_id,
				'add_time'=>time(),
			]);
			$msg = '收藏成功';
		}
		if($res === false){
		    return $result;
        }
		$result['code'] = 1;
		$result['msg'] = $msg;
		return $result;
	}

	/**
	 * @param $user_id
	 * @param $product_ids
	 * @return bool
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function Dels($user_id,$product_ids){
		$res = $this
			->where([
				['user_id','=',$user_id],
				['product_id','in',$product_ids],
			])
			->delete();

		return $res;
	}

	function GetMyCollection($user_id,$type = 1)
	{
		$where = [
			'c.user_id'=>$user_id,
			'p.is_del'=>1
		];
		$field = ['c.add_time','p.product_id','p.product_name','p.imageurl','p.sprice'];
		switch ($type) {
			case 1:
				$where['p.class_id']=1;
				$join = [
					['ddt_products p','c.product_id=p.product_id'],
				];
				break;
			case 2:
				$field[] = 'ps.p_s_name';
				$field[] = 'ps.p_s_id';
				$where['p.class_id']=4;
				$join = [
					['ddt_products_stock ps','c.p_s_id=ps.p_s_id'],
					['ddt_products p','ps.product_id=p.product_id'],
				];
				break;
		}

		$data = $this
			->alias('c')
			->field($field)
			->where($where)
			->leftJoin($join)
			->order('c.add_time desc')
			->paginate(6);

		return $data;
	}

    function get_list($field='*',$cond=null, $orderby='sort asc')
    {
		$where = null;

		if(!empty($cond['user_id'])){
			$where[] = ['user_id','=', $cond['user_id']];
		}

        $rs = $this
            ->field($field)
            ->where($where)
            ->order($orderby)
            ->select();
        return $rs;
    }

    function getOne($where=[1], $item='*')
    {
        $rs = $this
            ->field($item)
            ->where($where)
            ->find();

        return $rs;
    }

}